package cn.mifengkong.appcommon.webview.uicomponent;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.ColorInt;
import android.support.annotation.DrawableRes;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import com.mifengkong.frtools.jsbridge.BridgeHandler;
import com.mifengkong.frtools.jsbridge.CallBackFunction;
import com.mifengkong.frtools.jsbridge.JsHandler;
import com.mifengkong.frtools.jsbridge.webview.FRJSBridgeWebView;
import com.mifengkong.frtools.system.handler.FRMainLooperHandler;
import com.mifengkong.frtools.util.FRImageLoad;
import com.mifengkong.frtools.util.FRLog;
import com.mifengkong.frtools.util.FRString;
import com.mifengkong.frtools.util.NetWorkUtil;
import com.mifengkong.frwidget.dialog.FRDialog;
import com.mifengkong.frwidget.dialog.FRDialogClickListener;
import com.mifengkong.frwidget.titlebar.WebViewTitleBarUIComponent;
import com.mifengkong.frwidget.webview.BaseWebViewUIComponent;
import com.mifengkong.frwidget.webview.MediaUtility;
import com.mifengkong.frwidget.webview.MyWebChromeClient;
import com.mifengkong.frwidget.webview.MyWebViewDownLoadListener;
import com.yanzhenjie.permission.AndPermission;

import java.io.File;

import cn.mifengkong.appcommon.R;
import cn.mifengkong.appcommon.webview.BitmapDownloadIntentService;
import cn.mifengkong.appcommon.webview.JsLocalStorageConstantUtil;
import cn.mifengkong.appcommon.webview.jshandler.AliPayJsHandler;
import cn.mifengkong.appcommon.webview.jshandler.AuthorizeServiceJsHandler;
import cn.mifengkong.appcommon.webview.jshandler.CloseWebViewHandler;
import cn.mifengkong.appcommon.webview.jshandler.DefaultHandler;
import cn.mifengkong.appcommon.webview.jshandler.GetCreditApplyJsHandler;
import cn.mifengkong.appcommon.webview.jshandler.GoNativeHandler;
import cn.mifengkong.appcommon.webview.jshandler.ImageDownLoadHandler;
import cn.mifengkong.appcommon.webview.jshandler.LivingDetectionJSHandler;
import cn.mifengkong.appcommon.webview.jshandler.LuanchMiniProgramHandler;
import cn.mifengkong.appcommon.webview.jshandler.NavButtonHandler;
import cn.mifengkong.appcommon.webview.jshandler.PostDataHandler;
import cn.mifengkong.appcommon.webview.jshandler.RightBtnJsHandler;
import cn.mifengkong.appcommon.webview.jshandler.UmengShareHandler;
import cn.mifengkong.appcommon.webview.listener.JsBridgeCallBackListener;

import static android.app.Activity.RESULT_OK;
import static com.mifengkong.frtools.util.FRToast.getString;


/**
 * Created by jack on 17/5/12
 */

public class WebViewUIComponent extends RelativeLayout {

    private UmengShareHandler mUmengShareHandler;

    public WebViewUIComponent(Context context) {
        super(context);
    }

    public WebViewUIComponent(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public WebViewUIComponent(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    private BaseWebViewUIComponent webViewUIComponent;
    public MyWebChromeClient myWebChromeClient;
    private FRJSBridgeWebView webView;
    private NetWorkErrorUIComponent netWorkErrorUIComponent;
    private LinearLayout llLoading;
    private ImageView ivLoading;
    private ProgressBar progressBar;

    private WebviewDataConfig mWebviewDataConfig;

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        webView = findViewById(R.id.lw_webview);

        webViewUIComponent = BaseWebViewUIComponent.build(webView);
        llLoading = findViewById(R.id.aw_ll_loading);
        ivLoading = findViewById(R.id.aw_iv_loading);
        progressBar = findViewById(R.id.lw_progress_bar);
        netWorkErrorUIComponent = findViewById(R.id.lw_no_net_work);
        myWebChromeClient = new MyWebChromeClient(getContext(), progressBar);
        webViewUIComponent.setWebChromeClient(myWebChromeClient);
        MyWebViewDownLoadListener mDownLoadListener = new MyWebViewDownLoadListener(getContext());
        webViewUIComponent.setDownloadListener(mDownLoadListener);

        setWebViewLongClick();

        webView.setDefaultHandler(new DefaultHandler());
    }

    void setWebViewLongClick() {
        webView.setOnLongClickListener(new OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                WebView.HitTestResult result = ((WebView) v).getHitTestResult();
                if (null == result) {
                    return false;
                }
                int type = result.getType();
                if (type == WebView.HitTestResult.UNKNOWN_TYPE) {
                    return false;
                }
                // 相应长按事件弹出菜单
                // 这里可以拦截很多类型，我们只处理图片类型就可以了
                switch (type) {
                    case WebView.HitTestResult.PHONE_TYPE:
                        // 处理拨号
                        break;
                    case WebView.HitTestResult.EMAIL_TYPE:
                        // 处理Email
                        break;
                    case WebView.HitTestResult.GEO_TYPE:
                        // TODO
                        break;
                    case WebView.HitTestResult.SRC_ANCHOR_TYPE:
                        // 超链接
                        break;
                    case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
                        break;
                    case WebView.HitTestResult.IMAGE_TYPE:
                        // 处理长按图片的菜单项
                        // 获取图片的路径
                        String saveImgUrl = result.getExtra();
                        initSaveBitmapDialog(saveImgUrl);
                        break;
                    default:
                        break;
                }
                return true;
            }
        });
    }


    public void initConfig(WebviewDataConfig webviewDataConfig) {
        mWebviewDataConfig = webviewDataConfig;
    }

    public void initUserAgent(String version) {
        String userAgent = webViewUIComponent.getWebView().getSettings().getUserAgentString();
        userAgent = TextUtils.concat(userAgent, "fengrongAppAndiordAndPackageName" + getContext().getPackageName() + "AndVerison" + version).toString();
        webViewUIComponent.getWebView().getSettings().setUserAgentString(userAgent);
    }

    public void setWebViewGetTitle(MyWebChromeClient.OnGetTitleClick onGetTitleClick) {
        myWebChromeClient.setOnGetTitleClick(onGetTitleClick);
    }

    public void loadUrlAndData(String url) {
        if (!FRString.isEmpty(url)) {
            webViewUIComponent.loadUrl(url);
            FRLog.e("jiang", url);
        }
    }


    public void setProgressBarDrawable(@DrawableRes int resId) {
        progressBar.setProgressDrawable(ContextCompat.getDrawable(getContext(), resId));
    }

    public void setTvRefreshBackground(@DrawableRes int resId, @ColorInt int textColor) {
        netWorkErrorUIComponent.setTvRefreshBackground(resId, textColor);
    }

    public void refresh() {
        webViewUIComponent.reLoad();
    }

    public void setRefreshLayoutVisible(boolean isVisible) {
        netWorkErrorUIComponent.setVisibility(isVisible ? VISIBLE : GONE);
        setWebViewVisible(!isVisible);
    }

    public void setWebViewVisible(boolean isVisible) {
        webView.setVisibility(isVisible ? VISIBLE : GONE);
    }

    public void setRefreshOnClickListener(OnClickListener onClickListener) {
        netWorkErrorUIComponent.setRefreshOnClickListener(onClickListener);
    }

    public boolean isWebViewCanGoBack() {
        return webViewUIComponent.canGoBack();
    }

    public void goBack() {
        webViewUIComponent.goBack();
    }

    public BaseWebViewUIComponent getWebViewUIComponent() {
        return webViewUIComponent;
    }

    public void onDestroy() {
        try {
            if (webView != null) {
                removeView(webView);
                webView.removeAllViews();
                webView.destroy();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void showLoading() {
        llLoading.setVisibility(View.VISIBLE);
        setWebViewVisible(false);
        FRImageLoad.loadImageGif(R.drawable.icon_jump, ivLoading);
    }

    public void hideLoading() {

        llLoading.setVisibility(View.GONE);
        setWebViewVisible(true);
    }

    public void registerHandler(final String handlerName, final JsHandler handler) {
        webView.registerHandler(handlerName, new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                if (null != handler) {
                    handler.OnHandler(handlerName, data, function);
                }
            }
        });
    }

    public void initJsHandler(JsBridgeCallBackListener listener, WebViewTitleBarUIComponent titleBarUIComponent) {
        registerHandler(getString(R.string.js_handler_function_name_start_living_detection), new LivingDetectionJSHandler(listener));

        //注册h5中去登陆的方法，h5调原生的登陆
        registerHandler(getString(R.string.js_handler_function_name_gonative), new GoNativeHandler(getContext(), getContext().getPackageName(), listener));
        registerHandler(getString(R.string.js_handler_function_name_setrightbtn), new RightBtnJsHandler(getContext(), this, titleBarUIComponent, getContext().getPackageName(), listener));
        registerHandler(getString(R.string.js_handler_function_name_setNavButton), new NavButtonHandler(getContext(), this, titleBarUIComponent, getContext().getPackageName(), listener));
        registerHandler(getString(R.string.js_handler_function_name_postdata), new PostDataHandler(listener));
        registerHandler(getString(R.string.js_handler_function_name_closewebview), new CloseWebViewHandler(listener));

        registerHandler(getString(R.string.js_handler_function_apipay), new AliPayJsHandler(listener));
        registerHandler(getString(R.string.js_handler_function_authorizeService), new AuthorizeServiceJsHandler(listener));
        registerHandler(getString(R.string.js_handler_function_getCreditApplyJS), new GetCreditApplyJsHandler(listener));
        registerHandler(getString(R.string.js_handler_function_name_launch_mini_program), new LuanchMiniProgramHandler(listener));
        registerHandler(getString(R.string.js_handler_function_name_download_image), new ImageDownLoadHandler(getContext()));
        mUmengShareHandler = new UmengShareHandler(getContext());
        registerHandler(getString(R.string.js_handler_function_name_share), mUmengShareHandler);
    }


    public void setDataToLocalStorage() {
        if (null != mWebviewDataConfig) {
            final String jsUrl = JsLocalStorageConstantUtil.setDataToLocalStorageConstant(
                    mWebviewDataConfig.getUserId(),
                    mWebviewDataConfig.getToken(), mWebviewDataConfig.getPhone(),
                    mWebviewDataConfig.getPlatVersion(), mWebviewDataConfig.getPlatType(),
                    mWebviewDataConfig.getPackageName(), mWebviewDataConfig.getSourceId(),
                    mWebviewDataConfig.getAppUnionName(), mWebviewDataConfig.getCityId()
            );
            loadUrlAndData(jsUrl);
        }
    }

    public boolean startTelActivity(Activity activity, String url) {
        if (url.startsWith("tel:")) {
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            activity.startActivity(intent);
            return true;
        }
        return false;
    }

    public void requestPermission() {
        AndPermission.with(getContext())
                .requestCode(100)
                .permission(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.READ_PHONE_STATE,
                        Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                .callback(null).start();
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == MyWebChromeClient.FILECHOOSER_RESULTCODE) {
            if ((null == myWebChromeClient.mUploadMessage && null == myWebChromeClient.mUploadCallbackAboveL)) {
                return;
            }
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (myWebChromeClient.mUploadCallbackAboveL != null) {
                myWebChromeClient.onActivityResultAboveL(requestCode, resultCode, data);
            } else if (myWebChromeClient.mUploadMessage != null) {
                if (result != null) {
                    String path = MediaUtility.getPath(getContext(), result);
                    Uri uri;
                    if (!FRString.isEmpty(path)) {
                        uri = FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".fileprovider", new File(path));
                        myWebChromeClient.mUploadMessage
                                .onReceiveValue(uri);
                    }
                } else {
                    myWebChromeClient.mUploadMessage.onReceiveValue(myWebChromeClient.imageUri);
                }
                myWebChromeClient.mUploadMessage = null;
            }
        }
    }

    public void showNetErrorPage(String url) {
        boolean isErrorPage = !NetWorkUtil.isNetworkAvailable(getContext());
        if (!isErrorPage) {
            FRMainLooperHandler.getInstance().postDelayed(new Runnable() {
                @Override
                public void run() {
                    setRefreshLayoutVisible(false);
                }
            }, 200);
            getWebViewUIComponent().onPageFinished(url);
        } else {
            setRefreshLayoutVisible(true);
        }
    }

    /**
     * 低于android 8.0的需要手动loadURL，大于等于android 8.0直接返回false，否则无法重定向
     *
     * @return
     */
    public boolean shouldLoadingUrlByAndroidVersion() {
        return Build.VERSION.SDK_INT < 26;
    }

    public void userLogout() {
        FRMainLooperHandler.getInstance().postDelayed(new Runnable() {
            @Override
            public void run() {
                loadUrlAndData(JsLocalStorageConstantUtil.clearLocalStorageData());
            }
        }, 500);

    }

    /**
     * 开启硬件加速
     */
    public void startHardware() {
        webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
    }

    /**
     * 关闭硬件加速
     */
    public void stopHardware() {
        webView.setLayerType(View.LAYER_TYPE_NONE, null);
    }

    public void initSaveBitmapDialog(final String imageUrl) {
        new FRDialog.MDBuilder(getContext())
                .setMessage("是否需要保存图片到相册")
                .setNegativeContentAndListener("否", null)
                .setPositiveContentAndListener("是", new FRDialogClickListener() {
                    @Override
                    public boolean onDialogClick(View view) {
                        BitmapDownloadIntentService.startForSaveBasicInfo(getContext().getApplicationContext(), imageUrl);
                        return true;
                    }
                }).show();
    }

    public void onActivityStop() {
        if (mUmengShareHandler != null) {
            mUmengShareHandler.dialogDismiss();
        }
    }


}